<?php
/**
 * Created by PhpStorm.
 * Script Name: Mptag.php
 * Create: 2023/3/2 15:29
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use plugin\wechat\app\model\MpTag as TagM;
use plugin\wechat\app\service\Mp as MpService;
use plugin\wechat\app\service\MpTag as TagService;
use think\facade\Db;
use Support\Request;

class Mptag extends MpBase
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new TagM();
    }

    /**
     * 首页
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request)
    {
        $mp_info = $request->mpInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['mp_id', '=', $mp_info['id']]
            ];
            !empty($post_data['search_key']) && $where[] = [
                'name', 'like', '%' . $post_data['search_key'] . '%'
            ];
            $query = $this->model->where($where);
            $total = $query->count();
            if (! $total) {
                if(! is_string($res = TagService::tagList($mp_info))){
                    foreach ($res['tags'] as $tag){
                        $this->model->createOne([
                            'company_id' => $mp_info['company_id'],
                            'mp_id' => $mp_info['id'],
                            'tag_id' => $tag['id'],
                            'name' => $tag['name'],
                            'count' => $tag['count'],
                        ]);
                    }
                    $total = count($res['tags']);
                }
            }
            $list = $query->page($post_data['page'], $post_data['limit'])
                ->order('id', 'desc')
                ->select();
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->addTopButton('addnew')
            ->addTopButton('self', ['text' => '同步标签', 'href' => url('syncPost'), 'data-ajax' => true, 'data-confirm' => true])
            ->addTableColumn(['title' => 'tag id', 'field' => 'tag_id',  'minWidth' => 100])
            ->addTableColumn(['title' => '名称', 'field' => 'name', 'minWidth' => 100])
            ->addTableColumn(['title' => '粉丝数', 'field' => 'count', 'minWidth' => 100])
            ->addTableColumn(['title' => '创建时间', 'field' => 'create_time', 'minWidth' => 170])
            ->addTableColumn(['title' => '操作', 'minWidth' => 160, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete', ['href' => url('delPost', ['id' => '__data_id__'])]);

        return $builder->show();
    }

    /**
     * 新增标签
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savepost'))
            ->setTip("一个公众号，最多可以创建100个标签。")
            ->addFormItem('name', 'text', '标签名称', '30字符内', [], 'required maxlength=30');
        return $builder->show();
    }

    /**
     * 编辑
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(Request $request){
        if(! $data = $this->model->where([$this->tenantWhere(), $this->mpIdWhere()])->find(input('id'))){
            return $this->error('数据不存在');
        }
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savepost'))
            ->addFormItem('id', 'hidden', 'id', '')
            ->addFormItem('tag_id', 'hidden', 'tagid', '')
            ->addFormItem('name', 'text', '标签名称', '30字符内', [], 'required maxlength=30')
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost(Request $request, $jump = '', $data = [])
    {
        $mp_info = $request->mpInfo;
        $data = $request->post();
        Db::startTrans();
        try {
            if(empty($data[$this->pk])){
                $res = TagService::tagCreate($data['name']);
            }else{
                $res = TagService::tagUpdate($data['tag_id'], $data['name']);
            }
            if(is_string($res)){
                return $this->error($res, '', ['token' => token()]);
            }
            if(empty($data[$this->pk])){
                $data['company_id'] = $mp_info['company_id'];
                $data['mp_id'] = $mp_info['id'];
                $this->model->createOne($data);
            }else{
                $this->model->update($data);
            }
            Db::commit();
            return $this->success('操作成功！');
        }catch (\Exception $e){
            Db::rollback();
            return $this->error("操作失败：" . $e->getMessage(), '', ['token' => token()]);
        }
    }

    /**
     * 同步标签
     * @param Request $request
     * @return \support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function syncPost(Request $request){
        $mp_info = $request->mpInfo;
        if($request->isPost()){
            if(is_string($res = TagService::tagList($mp_info))){
                return $this->error($res);
            }
            foreach ($res['tags'] as $tag){
                TagService::syncDb($tag, $mp_info);
            }
            return $this->success('同步成功！');
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return \support\Response
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delPost(Request $request){
        $mp_info = $request->mpInfo;
        if($request->isPost()){
            if(! $data = $this->model->where([$this->tenantWhere(), $this->mpIdWhere()])->find(input('id'))){
                return $this->error('数据不存在');
            }
            if(is_string($res = TagService::tagDelete($data, $mp_info))){
                return $this->error($res);
            }
            return $this->success('操作成功！');
        }
    }
}